package org.shopping.web.commodity;

import org.apache.commons.beanutils.BeanUtils;
import org.shopping.domain.Commodity;
import org.shopping.service.commodity.impl.CommodityServiceImpl;
import org.shopping.utils.UUIDUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "AddCommodityController", value = "/AddCommodityController")
public class AddCommodityController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取提交的请求数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            // bean封装
            Commodity commodity = new Commodity();
            BeanUtils.populate(commodity, parameterMap);
            // 补全数据 : 主键cid
            commodity.setCid(UUIDUtils.randomKey());
            // 执行service业务层方法
            CommodityServiceImpl commodityService = new CommodityServiceImpl();
            boolean flag = commodityService.addCommodity(commodity);
            if (flag) {
                // 添加成功
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
